//
//  SpinnerPlugin.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/6/15.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import Moya
import UIKit

public final class SpinnerPlugin: PluginType {
    // 菊花进度条 展示的view
    private var view: UIView?
    
    private var isWindow = false
    
    // 菊花进度条
    private let spinner: UIActivityIndicatorView!
    
    public init(view: UIView? = nil) {
        
        self.spinner = UIActivityIndicatorView.init(style: .gray)
        
        if view != nil {
            self.view = view
            self.spinner.center = self.view!.center
            isWindow = false
        }else {
            UIWindow.keyWindow { v in
                self.view = v
                self.spinner.center = self.view!.center
                self.isWindow = true
            }
        }
        
    }
    
    // 开始发起请求
    public func willSend(_ request: RequestType, target: TargetType) {
        DispatchQueue.main.async {
            guard let parentView = self.view else {
                return
            }
            if (!parentView.subviews.contains(self.spinner)) {
                parentView.addSubview(self.spinner)
            }
            parentView.isHidden = false
            self.spinner.startAnimating()
        }
    }
    
    // 收到结果
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        //移除界面中央的活动状态指示器
        if self.isWindow {
           spinner.isHidden = true
        }else {
            spinner.removeFromSuperview()
        }
        spinner.stopAnimating()
    }
}

